<?php

class categories extends baseModel {
	
	private static $instance;
	
	function __construct() {
		parent::__construct ();
	}
	
	public static function newInstance() {
		if (! self::$instance instanceof self) {
			self::$instance = new self ();
		}
		return self::$instance;
	}
	
	function getTableName() {
		return 'categories';
	}
	
	function getCategoryCount($catID) {
		if (! isset ( $catID )) {
			return false;
		}
		static $count = 0;
		//check whether given category exisits
		$args = array ('category_id' => $catID );
		if ($this->exists ( $args )) {
		
		}
	}
	
	function insert($args) {
		// First get default values 
		if (count ( $args ) < 1) {
			return FALSE;
		}
		if ($args ['name'] == '') {
			return FALSE;
		}
		
		$cat_args = array (); // contains only fields for categories table
		// set default values
		$cat_args ['expiration_days'] = 0;
		$cat_args ['position'] = 0;
		$cat_args ['enabled'] = 1;
		$cat_args ['parent_id'] = 0;
		
		// contains fields for description categories
		$desc_args = array ();
		$desc_args ['locale_code'] = 'en_US';
		$desc_args ['name'] = '';
		$desc_args ['description'] = '&nbsp;';
		
		foreach ( $args as $key => $value ) {
			if (array_key_exists ( $key, $cat_args )) {
				$cat_args [$key] = $value;
			}
			if (array_key_exists ( $key, $desc_args )) {
				$desc_args [$key] = $value;
			}
		}
		// remove - from name to make it slug
		$args ['name'] = str_replace ( '-', " ", $args ['name'] );
		$parts = explode ( " ", $args ['name'] );
		foreach ( $parts as $key => $value ) {
			$str = preg_replace ( '#[^a-zA-Z0-9\s]#', '', $value );
			$str = trim ( $str );
			$parts [$key] = $str;
		}
		$slug = implode ( '-', $parts );
		
		unset ( $args ); // unset main argument array
		

		$columns = array ();
		$new_args = array ();
		$values = array ();
		foreach ( $cat_args as $key => $value ) {
			$columns [] = $key;
			$values [] = ':' . $key;
			$new_args [':' . $key] = $value;
		}
		
		$sql = sprintf ( 'INSERT INTO %s (' . implode ( ',', $columns ) . ') values (' . implode ( ',', $values ) . ')', $this->getTableName () );
		//echo $sql;
		//print_r($new_args);
		$result = $this->con->insert ( $sql, $new_args );
		if (! $result) {
			return FALSE;
		}
		$desc_args ['category_id'] = $this->last_insert_id ();
		
		$desc_args ['slug'] = $slug;
		print_r($desc_args);
		
		print_r($this->findBySlug($desc_args['slug']));
		$count=0;
		while ( $this->findBySlug ( $desc_args ['slug'] ) ) {
			$desc_args ['slug'] = $desc_args['slug'] . '_1';
			
		}
		
		
		$columns = array ();
		$new_args = array ();
		$values = array ();
		foreach ( $desc_args as $key => $value ) {
			$columns [] = $key;
			$values [] = ':' . $key;
			$new_args [':' . $key] = $value;
		}
		
		$sql = sprintf ( 'INSERT INTO %s (' . implode ( ',', $columns ) . ') values (' . implode ( ',', $values ) . ')', 'categories_description' );
		$result = $this->con->insert ( $sql, $new_args );
	}
	
	function deleteByID($id) {
		
		$args = array ();
		$args [':ID'] = $id;
		$sql = sprintf ( 'delete from %s WHERE category_id=:ID', $this->getTableName () );
		if ($this->con->delete ( $sql, $args )) {
			
			$sql = sprintf ( 'delete from %s WHERE category_id=:ID', 'categories_description' );
			$this->con->delete ( $sql, $args );
			
			// Now delete all the items of such category and then delete 
			// get all the subcategories is exists
			// check if subcategory exists
			if ($this->hasSubCategories ( $id )) {
				$subcategories = $this->findAllSubCategoriesByID ( $id );
				
				item::newInstance ()->deleteByCategoryID ( $subcategories );
				$sql = sprintf ( 'delete from %s WHERE category_id IN (%s)', $this->getTableName (), implode ( ',', $subcategories ) );
				
				$this->con->delete ( $sql, $args );
			}
		
		// then delete all subcategories of such category
		

		// now delete all the items of such cateogry
		//item::newInstance()->delete
		}
	}
	
	function exists($args=array()){
		if(!is_array($args)||count($args)<1){
			return false;
		}
		if(isset($args['id'])){
			return $this->findByID($args['id']);
			
		}else if (isset($args['slug'])){
			return $this->findBySlug($args['slug']);
		}else{
			return false;
		}
	}
	
	function deleteBySlug($slug) {
	
	}
	function hasItemsBySlug($slug) {
		$result = $this->findBySlug ( $slug );
		if ($result) {
			$ID = $result ['category_id'];
			return $this->hasItems ( $ID );
		} else {
			return false;
		}
	
	}
	
	function hasItems($id) {
		if ($id == '') {
			return false;
		}
		$args = array ();
		$args [] = $id;
		$items = item::newInstance ()->findByCategoryID ( $args );
		if ($items) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	function hasSubCategories($id) {
		$result = $this->findSubcategoriesByID ( $id );
		if ($result) {
			return true;
		} else {
			return false;
		}
	}
	
	function findBySlug($slug = '', $locale = 'en_US') {
		if ($slug == '') {
			return FALSE;
		}
		$args = array ();
		$args [':slug'] = $slug;
		$args [':locale'] = $locale;
		$sql = sprintf ( 'SELECT * FROM %s as cat INNER JOIN %s as dsc ON cat.category_id=dsc.category_id WHERE slug=:slug AND locale_code=:locale', $this->getTableName (), 'categories_description' );
		$result = $this->con->query ( $sql, $args );
		if ($result) {
			return $result [0];
		} else {
			return false;
		}
	}
	
	function findByID($ID = '', $locale = 'en_US') {
		if ($ID == '') {
			return FALSE;
		}
		$args = array ();
		$args [':ID'] = $ID;
		$args [':locale'] = $locale;
		$sql = sprintf ( 'SELECT * FROM %s as cat INNER JOIN %s as dsc ON cat.category_id=dsc.category_id WHERE cat.category_id=:ID AND locale_code=:locale', $this->getTableName (), 'categories_description' );
		$result = $this->con->query ( $sql, $args );
		if ($result) {
			return $result [0];
		} else {
			return false;
		}
	}
	
	function findTopCategories() {
		$args = array ();
		$locale = 'en_US';
		$args [':locale'] = $locale;
		$sql = sprintf ( 'SELECT * FROM %s as cat INNER JOIN %s as dsc ON cat.category_id=dsc.category_id WHERE locale_code=:locale AND parent_id=0 ', $this->getTableName (), 'categories_description' );
		return $this->con->query ( $sql, $args );
	}
	
	function findAll($locale = 'en_US') {
		$args = array ();
		$args [':locale'] = $locale;
		$sql = sprintf ( 'SELECT * FROM %s as cat INNER JOIN %s as dsc ON cat.category_id=dsc.category_id WHERE locale_code=:locale', $this->getTableName (), 'categories_description' );
		return $this->con->query ( $sql, $args );
	}
	
	function findSubcategoriesByID($parent_id) {
		if ($parent_id == '') {
			return false;
		}
		$locale = 'en_US';
		$args = array ();
		$args [':locale'] = $locale;
		$args [':parent_id'] = $parent_id;
		$sql = sprintf ( 'SELECT * FROM %s as cat INNER JOIN %s as dsc ON cat.category_id=dsc.category_id WHERE locale_code=:locale and parent_id=:parent_id', $this->getTableName (), 'categories_description' );
		return $this->con->query ( $sql, $args );
	}
	
	function findAllSubCategoriesByID($id) {
		if ($id == '') {
			return false;
		}
		
		$items = array ();
		
		//while (  ) {
		if ($this->hasSubCategories ( $id )) {
			$result = $this->findSubcategoriesByID ( $id );
			
			//print_r ( $result );
			//break;
			foreach ( $result as $i => $k ) {
				$items [] = $k ['category_id'];
				
				$items = array_merge ( $items, $this->deleteSubCategoriesByID ( $k ['category_id'] ) );
			
			}
		
		//$id = $result [0] ['category_id'];
		}
		
		return $items;
	}
	function deleteSubCategoriesByID($id) {
		
		if ($id == '') {
			return false;
		}
		
		$items = array ();
		
		//while (  ) {
		if ($this->hasSubCategories ( $id )) {
			$result = $this->findSubcategoriesByID ( $id );
			
			//print_r ( $result );
			//break;
			foreach ( $result as $i => $k ) {
				$items [] = $k ['category_id'];
				
				$items = array_merge ( $items, $this->deleteSubCategoriesByID ( $k ['category_id'] ) );
			
			}
		
		//$id = $result [0] ['category_id'];
		}
		
		return $items;
	
	}
	function tree() {
		$categories = array ();
		$sql = 'SELECT * FROM categories WHERE parent_id=0';
		$result = DB::newInstance ()->query ( $sql );
	}
	
	function toTree($id) {
		if ($id == '') {
			return false;
		}
		
		$items = array ();
		
		$item = $this->findByID ( $id );
		
		$childs = array ();
		if ($this->hasSubCategories ( $id )) {
			$result = $this->findSubcategoriesByID ( $id );
			
			//print_r ( $result );
			//break;
			foreach ( $result as $i => $k ) {
				$item ['child'] [] = $this->toTree ( $k ['category_id'] );
			
			}
		
		//$id = $result [0] ['category_id'];
		}
		//$item['child']=$childs;
		

		return $item;
	}
	
	function toTreeAll() {
		$categories = $this->findTopCategories ();
		$tree = array ();
		if ($categories) {
			foreach ( $categories as $i => $c ) {
				$tree [] = $this->toTree ( $c ['category_id'] );
			}
		}
		return $tree;
	}

}
